﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;

/// <summary>
/// Summary description for IM
/// </summary>
public class IM
{
    public IM()
    {
        //
        // TODO: Add constructor logic here
        //
    }
    /// <summary>
    /// Sets the message waiting in the query so the application knows to launch a window.
    /// </summary>
    /// <param name="sender">Sender of the message</param>
    /// <param name="recipient">Receiver of the Message</param>
    public static void setChatMessagesWaiting(string sender, string recipient)
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        CS_Code.IM_Notify_Temp nt = new CS_Code.IM_Notify_Temp();
        nt.dateTime = DateTime.UtcNow;
        nt.recipient = IM.LoginID(recipient);
        nt.sender = IM.LoginID(sender);
        db.IM_Notify_Temps.InsertOnSubmit(nt);
        db.SubmitChanges();
    }
    /// <summary>
    /// Takes the last 25 messages of the chat. and dissplays them out to the user.  It also takes any other messsages thats have been written and displays them out to the user.
    /// </summary>
    /// <param name="sender">the sender of the message</param>
    /// <param name="recipient">the receiver of the message</param>
    /// <param name="MaxUid">the id of the last message received from the database.</param>
    /// <returns>the formatted messages</returns>
    public static string[] getChatMessages(string sender, string recipient, string MaxUid)
    {
        string[] messagesRecipient = new string[2];
        MaxUid = MaxUid == string.Empty ? "0" : MaxUid; // if no ID make it 0.
        try
        {
            CS_Code.IMDataContext idb = new CS_Code.IMDataContext();
            var getMessagesRecipient = (from im in idb.IM_Messages
                                        where (((im.sender == IM.LoginID(sender) && im.recipient == IM.LoginID(recipient))) ||
                                           ((im.sender == IM.LoginID(recipient) && im.recipient == IM.LoginID(sender)))) && (im.uid > Convert.ToInt32(MaxUid))
                                        select new
                                        {
                                            sender = IM.UserName(im.sender),
                                            time_stamp = im.time_stamp,
                                            message = im.message,
                                            uid = im.uid
                                        }).ToArray();

            string UserN = HttpContext.Current.User.Identity.Name;
            //formats the messages for the users to see.
            for (int i = 0; i < getMessagesRecipient.Count(); i++)
            {
                if (recipient == getMessagesRecipient[i].sender) //if the recipient is the same as the sender, the message will be a different color.
                    messagesRecipient[0] += "<div class=\"spanSender\">" + getMessagesRecipient[i].sender + " [" + getMessagesRecipient[i].time_stamp.ToLongTimeString() + "]: " + getMessagesRecipient[i].message + "</div>";
                else
                    messagesRecipient[0] += "<div class=\"spanReceiver\">" + getMessagesRecipient[i].sender + " [" + getMessagesRecipient[i].time_stamp.ToLongTimeString() + "]: " + getMessagesRecipient[i].message + "</div>";
                messagesRecipient[1] = getMessagesRecipient[i].uid.ToString();
            }
            return messagesRecipient;
        }
        catch
        { }
        return messagesRecipient;
    }
    /// <summary>
    /// Inserts a message.
    /// </summary>
    /// <param name="message">message to input.</param>
    /// <param name="recipient">recipient of message</param>
    /// <param name="sender">sender of message</param>
    public static void ChatInsertMessages(string message, string recipient, string sender)
    {
        CS_Code.IMDataContext idb = new CS_Code.IMDataContext();
        CS_Code.IM_Message im = new CS_Code.IM_Message();
        im.message = message;
        im.recipient = IM.LoginID(recipient);
        im.sender = IM.LoginID(sender);
        im.time_stamp = DateTime.UtcNow;
        idb.IM_Messages.InsertOnSubmit(im);
        idb.SubmitChanges();
    }
    /// <summary>
    /// gets any group messages that have been stored.
    /// </summary>
    /// <param name="sender">sender of the messages</param>
    /// <param name="recipient">receiver of the messages</param>
    /// <param name="MaxUid">the last id of the messages received.</param>
    /// <returns>The formatted messages.</returns>
    public static string[] getGroupChatMessages(string sender, string recipient, string MaxUid)
    {
        string[] messagesRecipient = new string[2];
        MaxUid = MaxUid == string.Empty ? "0" : MaxUid;
        try
        {
            CS_Code.IMDataContext idb = new CS_Code.IMDataContext();
            var getMessagesRecipient = (from im in idb.IM_Messages
                                        where (im.recipient == new Guid(recipient)) && (im.uid > Convert.ToInt32(MaxUid))
                                        select new
                                        {
                                            sender = IM.UserName(im.sender),
                                            time_stamp = im.time_stamp,
                                            message = im.message,
                                            uid = im.uid
                                        }).ToArray();

            string UserN = HttpContext.Current.User.Identity.Name;

            for (int i = 0; i < getMessagesRecipient.Count(); i++)
            {
                if (sender == getMessagesRecipient[i].sender)
                    messagesRecipient[0] += "<div class=\"spanReceiver\">" + getMessagesRecipient[i].sender + " [" + getMessagesRecipient[i].time_stamp.ToLongTimeString() + "]: " + getMessagesRecipient[i].message + "</div>";
                else
                    messagesRecipient[0] += "<div class=\"spanSender\">" + getMessagesRecipient[i].sender + " [" + getMessagesRecipient[i].time_stamp.ToLongTimeString() + "]: " + getMessagesRecipient[i].message + "</div>";
                messagesRecipient[1] = getMessagesRecipient[i].uid.ToString();
            }
            return messagesRecipient;
        }
        catch
        { }
        return messagesRecipient;
    }
    /// <summary>
    /// Inserts a message.
    /// </summary>
    /// <param name="message">message to input.</param>
    /// <param name="recipient">recipient of message</param>
    /// <param name="sender">sender of message</param>
    public static void ChatGroupInsertMessages(string message, string recipient, string sender)
    {
        CS_Code.IMDataContext idb = new CS_Code.IMDataContext();
        CS_Code.IM_Message im = new CS_Code.IM_Message();
        im.message = message;
        im.recipient = new Guid(recipient);
        im.type = "group";
        im.sender = IM.LoginID(sender);
        im.time_stamp = DateTime.UtcNow;
        idb.IM_Messages.InsertOnSubmit(im);
        idb.SubmitChanges();
    }
    public static string checkMessages()
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var checkUserMessages = (from nt in db.IM_Notify_Temps
                                 where nt.recipient == IM.LoginID()
                                 select nt).FirstOrDefault();
        if (checkUserMessages != null)
        {
            string user = IM.UserName(checkUserMessages.sender);
            db.IM_Notify_Temps.DeleteOnSubmit(checkUserMessages);
            db.SubmitChanges();
            return user;
        }
        else
        {
            return string.Empty;
        }
    }

    /// <summary>
    /// Deletes any notifications of messages.
    /// </summary>
    /// <param name="sender">The sender of the message.</param>
    public static void deleteMessages(string sender)
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var checkUserMessages = (from nt in db.IM_Notify_Temps
                                 where nt.recipient == IM.LoginID() & nt.sender == IM.LoginID(sender)
                                 select nt);
        if (checkUserMessages != null)
        {
            db.IM_Notify_Temps.DeleteAllOnSubmit(checkUserMessages);
            db.SubmitChanges();
        }
    }
    /// <summary>
    /// Adds a room to the database.
    /// </summary>
    /// <param name="roomName">Room name.</param>
    public static void addRooms(string roomName)
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();

        var checkRoom = (from crr in db.IM_Chat_Rooms
                         where crr.room_name == roomName
                         orderby crr.uid descending
                         select crr).FirstOrDefault();

            CS_Code.IM_Chat_Room cr = new CS_Code.IM_Chat_Room();
            cr.userinRoom = IM.LoginID();
            cr.room_name = roomName;
            cr.Updated_DateTime = DateTime.UtcNow;
            if (checkRoom != null)
            {
                cr.room_ID = checkRoom.room_ID;
            }
            else
            {
                cr.room_ID = Guid.NewGuid();
            }
            db.IM_Chat_Rooms.InsertOnSubmit(cr);
            db.SubmitChanges();
    }

    /// <summary>
    /// resets the date and time of the room to keep the room alive.  If the date and time do not continually reset the time, the room will "die"
    /// </summary>
    /// <param name="recipient">The recipient of the room.</param>
    public static void setChatRoomTime(string recipient)
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var updateRoom = (from cr in db.IM_Chat_Rooms
                          where cr.room_ID == new Guid(recipient) && cr.userinRoom == IM.LoginID()
                          select cr).FirstOrDefault();
        if (updateRoom != null)
        {
            updateRoom.Updated_DateTime = DateTime.UtcNow;
        }
        else
        {
            var getRoom = (from cr in db.IM_Chat_Rooms
                           where cr.room_ID == new Guid(recipient)
                           select cr.room_name).FirstOrDefault();

            if (getRoom != string.Empty && getRoom != null)
            {
                CS_Code.IM_Chat_Room crr = new CS_Code.IM_Chat_Room();
                crr.room_ID = new Guid(recipient);
                crr.room_name = getRoom;
                crr.Updated_DateTime = DateTime.UtcNow;
                crr.userinRoom = IM.LoginID();
                db.IM_Chat_Rooms.InsertOnSubmit(crr);
            }
        }
        db.SubmitChanges();
    }
    /// <summary>
    /// Removes any old groups older than 15 seconds.  Enough time to wait and see if anyone has left the room.
    /// </summary>
    public static void RemoveOldGroups()
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        var deleteOldNames = (from cr in db.IM_Chat_Rooms
                              where cr.Updated_DateTime < DateTime.UtcNow.AddSeconds(-15) || cr.Updated_DateTime == null
                              select cr);
        db.IM_Chat_Rooms.DeleteAllOnSubmit(deleteOldNames);
        db.SubmitChanges();
    }
    /// <summary>
    /// The connection string of the system.
    /// </summary>
    /// <returns></returns>
    public static string ConnectionStringID()
    { return ConfigurationManager.ConnectionStrings["LocalSqlServer"].ConnectionString; }
    /// <summary>
    /// The user ID of the current logged in user.
    /// </summary>
    /// <returns>returns a Guid ID of the user.</returns>
        public static Guid LoginID()
    {
        MembershipUser mu = Membership.GetUser();
        return new Guid(mu.ProviderUserKey.ToString());
    }
    /// <summary>
    /// The user ID of the user name.
    /// </summary>
    /// <param name="userName">the user name to chack for the ID.</param>
    /// <returns>the Guid id of the user.</returns>
    public static Guid LoginID(string userName)
    {
        MembershipUser mu = Membership.GetUser(userName);
        return new Guid(mu.ProviderUserKey.ToString());
    }
    /// <summary>
    /// Gets the username of the user with their user ID.
    /// </summary>
    /// <param name="UserID">The Guid id of the user</param>
    /// <returns>Returns the username.</returns>
    public static string UserName(Guid UserID)
    {
        MembershipUser mu = Membership.GetUser(UserID);
        return mu.UserName;
    }
    /// <summary>
    /// Gets the user name of the currently logged in user.
    /// </summary>
    /// <returns>The user name.</returns>
    public static string UserName()
    {
        return HttpContext.Current.User.Identity.Name;
    }
    /// <summary>
    /// Gets the users online within the last 3 minutes.
    /// </summary>
    /// <returns>The amount of users online which includes the currently logged in user.</returns>
    public static int UsersOnline()
    {
        CS_Code.IMDataContext db = new CS_Code.IMDataContext();
        return (from au in db.aspnet_Users
                where au.LastActivityDate > DateTime.UtcNow.AddMinutes(-3)
                select au).Count();
    }
    /// <summary>
    /// Returns the web address and application path.  It operates between a secure port SSL encryption or just a regular web address.
    /// </summary>
    /// <returns>the web address of the current address in the domain bar.</returns>
    public static string Server_Port_Secure()
    {
        string ServerPortSecure = System.Web.HttpContext.Current.Request.ServerVariables["SERVER_PORT_SECURE"];
        string Address = "-1";
        string ApplicationPath = System.Web.HttpContext.Current.Request.ApplicationPath;
        if (ServerPortSecure == "0")
        {
            Address = "http://" + Server_Name() + ApplicationPath;
        }
        else if (ServerPortSecure == "1")
        {
            Address = "https://" + Server_Name() + ApplicationPath;
        }
        return Address;
    }
    /// <summary>
    /// The current Server name
    /// </summary>
    /// <returns>returns only the server name.</returns>
    public static string Server_Name()
    {
        return System.Web.HttpContext.Current.Request.ServerVariables["HTTP_HOST"];
    }

    /// <summary>
    /// Converts DateTime to yyyyMMdd Format
    /// </summary>
    /// <returns>a formatted date.</returns>
    public static string ConvertToyyyyMMdd()
    {
        return DateTime.UtcNow.ToString("yyyyMMdd");
    }
    /// <summary>
    /// Converts DateTime to yyyyMMdd Format
    /// </summary>
    /// <param name="datetime">Date and Time  to convert.</param>
    /// <returns>A formatted date.</returns>
    public static string ConvertToyyyyMMdd(DateTime datetime)
    {
        return datetime.ToString("yyyyMMdd");
    }
}
